package com.example.demo.service.impl;

import com.example.demo.entity.SearchHistory;
import com.example.demo.exception.DeleteFailure;
import com.example.demo.mapper.SearchHistoryMapper;
import com.example.demo.service.SearchHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SearchHistoryServiceImpl implements SearchHistoryService {

    private final SearchHistoryMapper searchHistoryMapper;

    @Autowired
    public SearchHistoryServiceImpl(SearchHistoryMapper searchHistoryMapper){
        this.searchHistoryMapper = searchHistoryMapper;
    }

    @Override
    public List<String> findByUserIdOrderBySearchTimeDesc(Long userId) {
        return searchHistoryMapper.searchHistoryByUserIdBySearchTimeDesc(userId).stream().map(SearchHistory::getKeyword).toList();
    }

    @Override
    public SearchHistory save(SearchHistory searchHistory) {
        searchHistoryMapper.insert(searchHistory);
        return searchHistoryMapper.selectById(searchHistory.getId());
    }

    @Override
    public void deleteByUserId(Long userId) throws DeleteFailure {
        if(searchHistoryMapper.deleteByUserId(userId) == 1){
            return ;
        }
        throw new DeleteFailure("删除该用户所有历史消息失败！");
    }
}
